/**
* @Title: TimeIntecepter.java
* @Package com.an.intecepter
* @Description: TODO(用一句话描述该文件做什么)
* @author antch,861710865@qq.com
* @date 2017年7月16日 下午8:59:30
* @version V1.0
*/


package com.an.intecepter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
* @ClassName: TimeIntecepter
* @Description: TODO(计算请求处理时间拦截器)
* @author antch,861710865@qq.com
* @date 2017年7月16日 下午8:59:30
*
*/
/*
 * 说明：继承HandlerInterceptorAdapter类，实现自定义拦截器
 */
@Component
public class TimeIntecepter extends HandlerInterceptorAdapter {

	/*
	 * (非 Javadoc)
	* <p>Title: preHandle</p>
	* <p>Description: 请求发生前执行</p>
	* @param request
	* @param response
	* @param handler
	* @return
	* @throws Exception
	* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		long startTime = System.currentTimeMillis();
		request.setAttribute("startTime", startTime);
		response.setCharacterEncoding("UTF-8");
		return super.preHandle(request, response, handler);
	}

	/*
	 * (非 Javadoc)
	* <p>Title: postHandle</p>
	* <p>Description:请求完成后执行 </p>
	* @param request
	* @param response
	* @param handler
	* @param modelAndView
	* @throws Exception
	* @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView)
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		long startTime = (long) request.getAttribute("startTime");
		request.removeAttribute("startTime");
		long endTime = System.currentTimeMillis();
		System.out.println("本次请求处理的时间：：" + (endTime - startTime));
		request.setAttribute("handlingTime", endTime - startTime);
		super.postHandle(request, response, handler, modelAndView);
	}
}
